
from colorama import Fore, Back, Style
from prettytable import PrettyTable
from datetime import datetime
import sqlite3
import json
import os


_print = None
userInput = None

SLM = ('''
  mmmm  m      m    m
 #"   " #      ##  ##
 "#mmm  #      # ## #
     "# #      # "" #
 "mmm#" #mmmmm #    #
 ''')

connDB = sqlite3.connect( 'base.sql' ) # конект с бд
cursor = connDB.cursor() # инициализация курсора

with open('userConfig.json', 'r') as jsf:
	config = json.load(jsf) # импорт конфига
	language = config["language"]

with open('./defaultConfigs/language/' + language + '.json', 'r') as f:
	config = json.load(f)
	help_c = config["help_c"]

	f_n = config ["f_n"]
	update = config["update"]
	areYouSure_c = config ["areYouSure_c"]
	bye = config["bye"]
	delmenu_c = config["delmenu_c"]

help_c = help_c["work_mode"] + '\n' + Fore.GREEN + help_c["read"] + Fore.BLUE + '\n' + help_c["write"] + Fore.YELLOW + '\n'+ help_c["update"] + Fore.MAGENTA + '\n' + help_c["deleteAll"] + '\n'+ Fore.RED + help_c["exit"] + Fore.RESET 





enter = '>SLM>'
inpt = 'input> '
delmenu = 'delMenu> '
upmenu = 'upMenu> '


# меню удаления
def upDate(userInput, _print):

	print( 'test help' )

	while True:
		_print = str( input( enter + upmenu ) )# input shell
		if _print != 'q':
			if _print == 'Execute':
				checkUp(_print)
			elif _print == 'Edit':
				changeContent(userInput, _print)
			elif _print == 'Group':
				egitGroup(userInput, _print)
		elif _print == 'q':
			break
		else:
			print( 'Unknown command: ' + _print + '\n' +'Enter \'help\'' )


# выполнение
def checkUp(_print):

	read()
	_print = str(input( update["stt"] ))
	toBase = [(_print)]
	cursor.execute(' UPDATE notes SET status = 1 WHERE id = ? ', toBase )
	connDB.commit()


# изменить запись
def changeContent(userInput, _print):

	read()
	_print = str(input( update["changeContent"] ))
	userInput = str(input( update["toChangeContent"] ))
	toBase = [userInput, _print]
	cursor.execute(' UPDATE notes SET content = ? WHERE id = ? ', toBase )
	connDB.commit()


# изменить группу
def egitGroup(userInput, _print):
	read()
	_print = str(input( update["changeContent"] ))
	userInput = str(input( update["group"] ))
	toBase = [userInput, _print]
	cursor.execute(' UPDATE notes SET groups = ? WHERE id = ? ', toBase )
	connDB.commit()

def timer(userInput, _print):
	read()
	

def editTimer(userInput, _print):
	pass

# меню удаления записей
def delMenu(_print):

	print( 'test help' )

	while True:
		_print = str( input( enter + delmenu ) )# input shell
		if _print != 'q':
			if _print == 'del':
				delete(_print)
			elif _print == 'delAll':
				deleteAll(_print)
		elif _print == 'q':
			break
		else:
			print( 'Unknown command: ' + _print + '\n' +'Enter \'help\'' )


# построное удаление
def delete(_print):

	read()
	# _print = str(input( delmenu["delete"] ))
	_print = str(input( delmenu_c['delete_c'] ))
	toBase = [(_print)]
	cursor.execute(' DELETE FROM notes WHERE id = ? ', toBase)
	connDB.commit()

# полное удаление
def deleteAll(_print):

	areYouSure = str( input( areYouSure_c ) )# подтвеждение
	if areYouSure == 'yes':
		cursor.execute(' DELETE FROM notes ')# удаление файла
		connDB.commit()
	else:
		pass




# чтение наших записей
def read():

	table = PrettyTable() # иниациализируем вывод в таблицу
	cursor.execute(' SELECT * FROM notes WHERE status = 0 ') # выбираем все записи
	result = cursor.fetchall()
	table.field_names = [ f_n['id'], f_n['content'], f_n['time'], f_n['date'], f_n['status'], f_n['group'] ] # прописываем столбцы
	for item in result: # собираем вывод
		table.add_row( [ item[0], item[1], item[2], item[3], item[5], item[4] ] )
	table.align = 'c'
	table.align['Id'] = 'r'
	print( table ) # распечатываем


# запись в таблицу
def write(userInput):

	while True:
		userInput = str( input( enter + inpt ) )# инпут шелл
		if userInput != 'q':
			time = str(input( config["time"] ))
			date = str(input( config["date"] ))
			
			if time == '':
				time = '---'
			if date == '':
				date = '---'

			# now = datetime.today()
			# time = now.strftime( '%H:%M' )# время
			# date = now.strftime( '%d.%m.%Y' )# дата
			status = False
			toBase = [(userInput, date, time, status)]
			cursor.executemany(' INSERT INTO notes ( content, date, time, status ) VALUES ( ?, ?, ?, ? )', toBase ) # отправляем в таблицу
			connDB.commit()# подтверждаем
		elif userInput == 'q': # условие выхода
			break
		else:
			pass


# очиска терминала
def clearShell():
	os.system(['clear'][os.name == os.sys.platform])

# хелп
def helper():
	print( help_c )

# собирательная функция
def menu(_print, userInput):

	while True:
		_print = input( enter )
		if _print == 'r':
			read()
		elif _print == 'w':
			write(userInput)
		elif _print == 'd':
			delMenu(_print)
		elif _print == 'u':
			upDate(userInput, _print)
		elif _print == 'q':
			break
		elif _print == 'help':
			helper()
		elif _print == 'clear':
			clearShell()
		else:
			print( 'Unknown command: ' + _print + '\n' +'Enter \'help\'' )

clearShell()

print( Fore.GREEN + config["welkome"] + Fore.RESET )
print( help_c )


menu(_print, userInput)
connDB.close()# закрытие конекта
clearShell()
print( bye + '\n' + SLM )
